package com.zidongxiangxi.rabbit.starter.util;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * zookeeper工具类
 *
 * @author chenxudong
 * @date 2020/11/08
 */
public class ZookeeperUtils {
	private static final Logger logger = LoggerFactory.getLogger(ZookeeperUtils.class);
	private static final String BASE_ZOOKEEPER_PATH_PREFIX = "/reliable_rabbit/lock/";

	public static CuratorFramework createCuratorFramework(String zookeeperAddress, int baseSleepTimeMs,
														  int maxRetries) {
		try {
			RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries);
			CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(zookeeperAddress, retryPolicy);
			curatorFramework.start();
			return curatorFramework;
		} catch (Throwable e) {
			logger.error("创建CuratorFramework失败，zookeeper地址为:" + zookeeperAddress, e);
		}
		return null;
	}

	public static void closeCuratorFramework(CuratorFramework client) {
		if (Objects.nonNull(client)) {
			client.close();
		}
	}

	public static InterProcessMutex getLock(CuratorFramework client, String path) {
		return new InterProcessMutex(client, BASE_ZOOKEEPER_PATH_PREFIX + path);
	}
}
